# encoding=utf-8

import code, time, six, websocket, json
from instruction import ins_login, ins_register

OPCODE_DATA = (websocket.ABNF.OPCODE_TEXT, websocket.ABNF.OPCODE_BINARY)

class Bot(object):
    def __init__(self, addr, uname, pwd):
        self.ws = None
        
        self.prepare = None
        self.task = None

        self.addr = addr
        self.username = uname
        self.password = pwd
    
    def login(self): 
        self.ws = websocket.create_connection(self.addr)
        self._send(ins_login(self.username, self.password)[0])
        rr = self.recv_data()
        resp = json.loads(rr)
        if resp['id'] == '100017':
            print '[%s] 登录成功' % self.username
            print '[%s] 登录消息: %.80s' % (self.username, self.recv_data())
            return True
        elif resp['id'] == '100052':
            print '[%s] 开场剧情...' % self.username
            return 'LOGIN_NEWGUIDE'
        else:
            print rr
            print '[%s] 登录失败，%s' % (self.username, resp['errmsg'].encode('utf-8'))
            return False

    def register(self):
        self.ws = websocket.create_connection(self.addr)
        self._send(ins_register(self.username, self.password)[0])
        resp = json.loads(self.recv_data())
        
        if resp['res'] == 0:
            # Register failed:
            print '[%s] 注册失败，%s' % (self.username, resp['errmsg'].encode('utf-8'))
            return False
        elif resp['res'] == 1:
            print '[%s] 注册成功，密码：%s' % (self.username, self.password)
            return True
        return False

    def set_addr(self, addr):
        self.addr = addr

    def set_prepare(self, prepare):
        self.prepare = prepare

    def set_task(self, task, interval, times = -1):
        self.task = task
        self.interval = interval
        self.times = times

    def stop_task(self, task):
        pass

    def sync_start(self):
        # exec prepae
        if self.prepare != None:
            self.prepare(self)
            
        if self.times >= 0:
            while self.times > 0:
                time.sleep(self.interval)
                self.task(self)
                self.times -= 1    
        else:
            while True:
                time.sleep(self.interval)
                self.task(self)

    def send_ins(self, Ins):
        for m in Ins:
            self._send(m)
            self.recv_data()

    def send(self, Msg):
        return self._send(Msg)

    def recv_data(self):
        opcode, data = self._recv()
        print '[%s] RECV: %.100s' % (self.username, data)

        return data

    def _send(self, Msg):
        print '[%s] SEND: %.100s' % (self.username, Msg)
        return self.ws.send(Msg)

    def _recv(self):
        try:
            frame = self.ws.recv_frame()
        except websocket.WebSocketException:
            return websocket.ABNF.OPCODE_CLOSE, None
        if not frame:
            raise websocket.WebSocketException("Not a valid frame %s" % frame)
        elif frame.opcode in OPCODE_DATA:
            return frame.opcode, frame.data
        elif frame.opcode == websocket.ABNF.OPCODE_CLOSE:
            ws.send_close()
            return frame.opcode, None
        elif frame.opcode == websocket.ABNF.OPCODE_PING:
            ws.pong(frame.data)
            return frame.opcode, frame.data

        return frame.opcode, frame.data
